// pages/layout/layout.js
Page({
  data: {
    imagesData: [],
    screenWidth: 0,
    screenHeight: 0
  },
 forceLayout :function (imagesData, width, height, iterations = 3) {
    const springConstant = 0.001; // 弹簧常数
    const gravity = 0.01; // 重力加速度
    const friction = 0.95; // 摩擦系数
    console.log(imagesData, width, height)
    // 初始化位置
    imagesData.forEach((image, index) => {
      image.x = Math.random() * width/2;
      image.y = Math.random() * height/2;
      image.vx = 0;
      image.vy = 0;
    });
  
    for (let i = 0; i < iterations; i++) {
      imagesData.forEach((image, index) => {
        let fx = 0, fy = 0;
  
        // 计算重力
        fy += gravity * image.height;
  
        // 计算弹簧力
        imagesData.forEach((otherImage, j) => {
          if (index !== j) {
            const dx = otherImage.x - image.x;
            const dy = otherImage.y - image.y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            const force = springConstant * (distance - 100); // 假定每个图片间的理想距离为100
            fx += force * dx / distance;
            fy += force * dy / distance;
          }
        });
  
        // 更新速度和位置
        image.vx += fx;
        image.vy += fy;
        image.vx *= friction;
        image.vy *= friction;
        image.x += image.vx;
        image.y += image.vy;
        // 碰壁反弹
        if (image.x < 0 || image.x > width) {
          image.vx *= -1;
          image.x += image.vx;
        }
        if (image.y < 0 || image.y > height) {
          image.vy *= -1;
          image.y += image.vy;
        }
      });
    }
  
    return imagesData;
  } ,
  onLoad: function () {
    const imagesData = [
      { url: '../../../img/com.png', width: 20, height: 20 },
      { url: '../../../img/cygl.png', width: 20, height: 20 },
      // 更多图片...
    ];
    console.log(imagesData)
    this.setData({ 
      imagesData:imagesData });
    const that = this;
    that.imagesData= imagesData;
    console.log(that.imagesData)
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          screenWidth: res.windowWidth,
          screenHeight: res.windowHeight
        });
        that.layoutImages();
      }
    });
  },

  layoutImages: function () {
    const imagesData = this. forceLayout(
      this.data.imagesData,
      this.data.screenWidth,
      this.data.screenHeight
    );
    this.setData({ imagesData });
  }
});